package cloud.daodao.storm.common.util.io;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CommandUtil {

    public static String[] exec(String[] commands) {
        try {
            log.info("commands: {}", String.join(" ", commands));
            // 执行命令
            Process process = Runtime.getRuntime().exec(commands);

            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            List<String> lines = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }

            // 等待命令执行完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("exitCode: " + exitCode);
            }

            // 关闭 reader
            reader.close();
            String[] results = lines.toArray(new String[0]);
            log.info("results: {}", String.join("\n", results));
            return results;
        } catch (IOException | InterruptedException e) {
            log.error(e.getMessage(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }

    }

}
